import {formVerify} from "../../../utils/util"
const defaultSettings = require('../../../config/defaultSettings')
Component({
  options: {
    styleIsolation: 'shared',
  },
  lifetimes: {
    attached:function() {
      if(this.data.formData[this.data.field['field']+this.data.betweenSign]){
        this.init()
      }
    }
  },
  observers:{
    'formData':function(formData){
      this.init()
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    formData:{
      type:Object,
      value:{}
    },
    field:{
      type:Object,
      value:{}
    },
    betweenSign:{
      type:String,
      value:""
    },
   
  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList:[],
    errorMessage:'',
    defaultSettings,
    openTimer:null,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init(){
      if(this.data.formData[this.data.field['field']+this.data.betweenSign]){
        let dbFileUrls = this.data.formData[this.data.field['field']+this.data.betweenSign].split(",")
        let fileList=[]
        let file = {}
        for(var url of dbFileUrls){
          file.status = 'done';
          file.message = '上传成功...'
          file.url=defaultSettings.fileServer+'/'+url
          file.dbUrl=url
          fileList.push(file)
        }
        this.setData({fileList:fileList})
      }
      
    },
    onOversize(){
      wx.showToast({
        icon:"none",
        title: "文件大小不能超过50M",
      })
      return false
    },
    onDelete(e){
      let index = e.detail.index
      let fileList = this.data.fileList
      fileList.splice(index,1)
      this.setData({fileList:fileList},()=>{this.setFormData()})
    },
    onClick(e){
      let {index} = e.detail
      let that = this
      let url =  that.data.fileList[index]["url"]
      // console.log(url)
      const sufInx = url.lastIndexOf(".");
      if (sufInx === -1) {
        uni.showModal({
          title: '提示信息',
          content: '文件错误！',
          success: function(res) {
            if (res.confirm) {
              //console.log('用户点击确定');
            } else if (res.cancel) {
              //console.log('用户点击取消');
            }
          }
        });
        return false
      }
      let fileType = url.substring(sufInx + 1)
      // console.log(fileType)
      if(defaultSettings.uploadImageType.indexOf(fileType.toLowerCase())<0 && defaultSettings.uploadFileType.indexOf(fileType.toLowerCase())<0){
        wx.showLoading({
          title: fileType+'文件类型不支持',
          mask:true,
        })
        return false
      }
      wx.downloadFile({
        url: url,
        success (res) {
          if (res.statusCode === 200) {
            // console.log(res.tempFilePath)
            wx.showLoading({
              title: '',
              mask:true,
            })
            setTimeout(() => {
              wx.hideLoading()
              wx.openDocument({
                filePath: res.tempFilePath,
                fileType: fileType,
                showMenu: true,
                success: function () {
                    //打开成功
                    // console.log('成功')
                },
                fail(rr){
                  //打开失败
                  // console.log("打开失败")
                  wx.showToast({
                    icon:'error',
                    title: '文件打开失败',
                  })
                },
                complete(){
                  wx.hideLoading()
                }
              })
            }, 1000);
            
          }else{
            //下载失败
            wx.showToast({
              icon:'error',
              title: '文件下载失败',
            })
          }
        },
        fail(res){
          //下载失败
          wx.showToast({
            icon:'error',
            title: '文件下载失败',
          })
        }
      })
    },
    beforeRead(e){
      const { file, callback } = e.detail
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf(".")+1)
      if(defaultSettings.uploadImageType.indexOf(file.type.toLowerCase())>-1){
        callback(true)
      }else if(defaultSettings.uploadFileType.indexOf(fileType.toLowerCase())>-1){
        callback(true)
      }else{
        wx.showToast({
          icon:'error',
          title: '不支持'+fileType+'文件类型',
        })
        callback(false)
      }
    
    },
    afterRead(e){
      wx.showLoading({
        title: '上传中...',
        mask:true,
      })
      let that = this
      const {file} = e.detail
      file.status = 'uploading'
      file.message = '上传中...'
      let uploadTask = wx.uploadFile({
        filePath: file.url,
        name: 'file',
        url: defaultSettings.uploadServer,
        header:{
          'content-type':"multipart/form-data"
        },
        success(res){
          wx.hideLoading()
          let r = JSON.parse(res.data)
          file.status = 'done';
          file.message = '上传成功...'
          file.url=defaultSettings.fileServer+'/'+r.message
          file.dbUrl = r.message
          const  fileList  = that.data.fileList
          fileList.push(file)
          that.setData({ fileList:fileList },()=>{that.setFormData()})
        },
        fail(res){
          wx.hideLoading()
          file.status = 'failed';
          file.message = '上传失败'
          wx.showToast({
            icon:'error',
            title: '文件上传失败',
          })
        },
        complete(){
          wx.hideLoading()
        }

      })
      // 监听上传进度
      // uploadTask.onProgressUpdate(function (res) {
      //   console.log('上传进度：' + res.progress + '%');
      //   console.log('已经上传的数据长度：' + res.totalBytesSent);
      //   console.log('预期需要上传的数据总长度：' + res.totalBytesExpectedToSend);
      
      // });
    },
  
    setFormData(){
      let dbUrls=""
      for(var f of this.data.fileList){
        dbUrls += f.dbUrl+","
      }
      if(dbUrls!=""){
        dbUrls =dbUrls.slice(0, -1);
      }
      this.data.formData[this.data.field['field']+this.data.betweenSign]=dbUrls
      //调用父级，将值传出
      this.triggerEvent("change",{field:this.data.field['field']+this.data.betweenSign,val:dbUrls})
      this.verify()
    
    },
    verify(){
      return formVerify(this)
    }
  }
})
